package com.sdleyou.treepro.common.service.impl;

import com.sdleyou.treepro.common.model.dao.Page;
import com.sdleyou.treepro.common.service.MongoPageManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MongoPageManagerImpl implements MongoPageManager {
    public static final int FIRST_PAGE_NUM = 1;
    public static final String ID = "_id";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public <T> Page pageQuery(Query query, Class<T> entityClass, Integer pageSize, Integer pageNum) {
        if (pageNum <= 0) {
            pageNum = FIRST_PAGE_NUM;
        }
        final Criteria criteria = new Criteria();
        Long totalCount = mongoTemplate.count(query, entityClass);

        int skip = pageSize * (pageNum - 1);
        query.skip(skip).limit(pageSize);
        final List<T> entityList = mongoTemplate
                .find(query.addCriteria(criteria),
                        entityClass);
        return new Page(pageNum, totalCount, pageSize, entityList);
    }

    @Override
    public <T> Page pageQuery(Query query, Class<T> entityClass, Integer pageSize, Integer pageNum, String collName) {
        if (pageNum <= 0) {
            pageNum = FIRST_PAGE_NUM;
        }
        final Criteria criteria = new Criteria();
        Long totalCount = mongoTemplate.count(query, entityClass, collName);

        int skip = pageSize * (pageNum - 1);
        query.skip(skip).limit(pageSize);
        final List<T> entityList = mongoTemplate
                .find(query.addCriteria(criteria),
                        entityClass, collName);

        return new Page(pageNum, totalCount, pageSize, entityList);
    }
}
